<!-- 合同文本 -->
<template>
  <div class="wrap">
    <section class="" v-if="tabs.data[currUserId]">
      <a-tabs
        @change="tabsChange"
        v-model:active-key="currTab"
        :default-active-key="tabs.data[currUserId][0]?.uid"
      >
        <a-tab-pane
          v-for="item in tabs.data[currUserId]"
          :key="item.uid"
          :title="item.name"
        >
          <RichTextNew
            v-model:content="item.text"
            :ref="(el) => setItemRef(el, item.uid)"
            :name="`rich${item.uid}`"
          ></RichTextNew>
        </a-tab-pane>
        <!-- <a-tab-pane key="1" title="Tab 1">
          <RichTextNew
            v-model:content="formData.designData.text"
            ref="rich"
          ></RichTextNew>
        </a-tab-pane>
        <a-tab-pane key="2" title="Tab 2"> Content of Tab Panel 2 </a-tab-pane>
        <a-tab-pane key="3">
          <template #title>Tab 3</template>
          Content of Tab Panel 3
        </a-tab-pane> -->
      </a-tabs>
    </section>
    <section class="control">
      <a-scrollbar style="height: calc(100vh - 260px); overflow: auto">
        <section>
          <h3>已选人员</h3>
          <a-space wrap>
            <a-radio-group v-model="currUserId" @change="userChange">
              <a-radio
                v-for="item in formData.userData"
                :key="item.id"
                :value="item.id"
              >
                <template #radio="{ checked }">
                  <a-tag
                    size="large"
                    :class="{ 'custom-radio-card-checked': checked }"
                    :checked="checked"
                    class="custom-radio-card"
                    checkable
                    >{{ item.name }}</a-tag
                  >
                </template>
              </a-radio>
            </a-radio-group>
          </a-space>
          <a-divider />
        </section>
        <a-input-search
          v-model="searchVal"
          search-button
          @input="onSearch"
          @press-enter="onSearch"
          placeholder="快速搜索变量"
        ></a-input-search>
        <section v-for="item in currControlData" :key="item.id">
          <h3>{{ item.subDetail.cnName }}</h3>
          <a-space wrap>
            <a-button
              v-for="(item2, index2) in item.subDetail.subRelDetail"
              :key="item2.id"
              @click="inputLabel(item2, index2)"
              >{{ item2.ctlCnName }}
            </a-button>
          </a-space>
          <a-divider />
        </section>
      </a-scrollbar>
    </section>
  </div>
</template>

<script setup lang="ts">
import { GetBusinessModalData } from '@/apis/controltotal';
import { cloneDeep } from 'lodash';
import { changeControlData } from '@/utils/control';
import { useVModel } from '@vueuse/core';
import { GetContractTemplateDetail } from '@/apis/management/contract/baseSetting';

const props = withDefaults(
  defineProps<{
    data: any;
  }>(),
  {}
);
const emit = defineEmits(['update:visible', 'update:data', 'handleOk', 'save']);
const formData = useVModel(props, 'data', emit);

// const formData = ref({
//   text: '',
//   codes: []
// });

let originControlData = ref([]), // 储存原始控件信息
  currControlData = ref<any>([]), // 储存当前控件信息
  searchVal = ref(''),
  currUserId = ref(), // 当前选中的人员id
  selectedUserInfo = []; // 选中人员的ids
const getData = async () => {
  const { funcCtlInfos } = (await GetBusinessModalData({
    funcCode: 'SER_FUNC751D0BFF5DF442209D437EE9A581693E'
  })) as any;
  controlList.value = changeControlData(funcCtlInfos, 'ctlDetail');
  originControlData.value = funcCtlInfos.children;
  currControlData.value = cloneDeep(funcCtlInfos.children);
};
getData();

let itemRefs: any = {}; // 储存动态生成的富文本ref
let currUid = ref(); // 储存当前选中tab的uid
let currTab = computed(() => currUid.value);
let currIndex = 0;
// 动态设置富文本ref
const setItemRef = (el: any, uid: number) => {
  itemRefs[uid] = el;
};

// 改变标签
const tabsChange = (key: string) => {
  currUid.value = key;
  currTab.value = currUid.value;
  // for (let [item, index] of tabs.data[currUserId.value]) {
  //   if (item.uid === currUid.value) {
  //     currIndex = index;
  //     break;
  //   }
  // }

  for (let i = 0; i < tabs.data[currUserId.value].length; i++) {
    if (tabs.data[currUserId.value][i].uid === currUid.value) {
      currIndex = i;
      break;
    }
  }
};

let codes: any = []; // 储存当前选择的控件
// tab选项初始数据
let controlList: any = ref();

let tabs: any = reactive({ data: [] });
const tabsId: any = reactive([]);

// 获取合同模板详情
const getContractDetail = async (id: number) => {
  try {
    const res = await GetContractTemplateDetail({ id });
    return res;
  } catch (error: unknown) {
    console.log(error);
  }
};

watch(
  () => props.data.userData,
  (newVal: any) => {
    if (newVal.length > 0) {
      selectedUserInfo = [];
      newVal.forEach((el: any) => {
        selectedUserInfo.push({
          id: el.id,
          name: el.name
        });
      });
      currUserId.value = newVal[0].id;
    }
  },
  {
    deep: true
    // flush: 'pre'
  }
);

watch(
  () => props.data.baseInfoData,
  async (val) => {
    const {
      templateName: name,
      templateId: uid,
      annexData,
      templateInfo
    } = val;
    for (let i of selectedUserInfo) {
      let contractRes;
      // let contractRes = await getContractDetail(uid);
      if (!tabs.data[i.id]) {
        console.log(11111, selectedUserInfo, annexData);
        contractRes = templateInfo;
        tabs.data[i.id] = [];
        tabs.data[i.id][0] = {
          // id: templateInfo.id,
          userInfo: {
            id: i.id,
            name: i.name
          },
          name,
          uid: `${i.id}-${uid}`,
          text: contractRes?.text,
          codes: contractRes?.codes,
          logo: contractRes?.logo,
          style: contractRes?.style,
          typeId: contractRes?.typeId,
          enterpriseName: contractRes?.enterpriseName
        };
        currUid.value = tabs.data[i.id][0].uid;

        for (let [index, el] of annexData.entries()) {
          let annexRes;
          annexRes = el;
          // const annexRes = await getContractDetail(el.id);
          tabs.data[i.id][index + 1] = {
            // id: el.id,
            userInfo: {
              id: i.id,
              name: i.name
            },
            name: el.name,
            uid: `${i.id}-${el.typeId}-${el.id}`,
            text: annexRes?.text,
            codes: annexRes?.codes,
            logo: annexRes?.logo,
            style: annexRes?.style,
            typeId: annexRes?.typeId,
            enterpriseName: annexRes?.enterpriseName
          };
          tabsId.push(`${i.id}-${el.typeId}-${el.id}`);
        }
      } else {
        editTabs(val, i);
        // console.log(
        //   '====================================currTabcurrTabcurrTab'
        // );
        // console.log(tabs.data);
        // console.log(currTab.value);
        // console.log('====================================');
      }
    }
  },
  {
    deep: true
    // flush: 'pre'
  }
);
const editTabs = async (data: any, userInfo: any) => {
  try {
    console.log(22222);

    console.log('====================================userInfo');
    console.log(tabs.data[userInfo.id], userInfo);
    console.log('====================================');
    const newData = {
      [userInfo.id]: []
    };

    const {
      templateName: name,
      templateId: uid,
      annexData,
      templateInfo
    } = data;

    if (
      !(tabs.data[userInfo.id][0].uid === `${userInfo.id}-${data.templateId}`)
    ) {
      const contractRes = await getContractDetail(uid);

      newData[userInfo.id][0] = {
        userInfo,
        name,
        uid: `${userInfo.id}-${data.templateId}`,
        text: contractRes?.text,
        codes: contractRes?.codes,
        logo: contractRes?.logo,
        style: contractRes?.style,
        typeId: contractRes?.typeId,
        enterpriseName: contractRes?.enterpriseName
      };
    } else {
      newData[userInfo.id][0] = tabs.data[userInfo.id][0];
    }

    const editIds: any = [];
    const isIds: any = [];
    annexData.forEach((ele: any) => {
      editIds.push(`${userInfo.id}-${ele.typeId}-${ele.id}`);
    });

    Array.from(tabs.data[userInfo.id]).forEach((ele: any, index: number) => {
      if (index) {
        if (editIds.includes(ele.uid)) {
          newData[userInfo.id].push(ele);
          isIds.push(ele.uid);
        }
      }
    });
    for (let ele of annexData) {
      if (!isIds.includes(`${userInfo.id}-${ele.typeId}-${ele.id}`)) {
        const annexRes = await getContractDetail(ele.id);
        newData[userInfo.id].push({
          userInfo,
          name: ele.name,
          uid: `${userInfo.id}-${ele.typeId}-${ele.id}`,
          text: annexRes?.text,
          codes: annexRes?.codes,
          logo: annexRes?.logo,
          style: annexRes?.style,
          typeId: annexRes?.typeId,
          enterpriseName: annexRes?.enterpriseName
        });
      }
    }
    tabs.data[userInfo.id] = { ...newData[userInfo.id] };
    currUid.value = tabs.data[userInfo.id][0].uid;
  } catch (error: unknown) {
    console.log(error);
  }
};

const userChange = (key: number) => {
  currUserId.value = key;
  currTab.value = tabs.data[currUserId.value][0].uid;
  currIndex = 0;
};

// 搜索框
const onSearch = () => {
  currControlData.value = [];
  if (searchVal.value === '') {
    currControlData.value = cloneDeep(originControlData.value);
  } else {
    for (let item of originControlData.value) {
      item.subDetail.subRelDetail.forEach((item2: any) => {
        if (item2.ctlCnName.includes(searchVal.value)) {
          // 判断如果该控件所属的子集不存在，则创建一个子集，否则直接将控件信息赋值给subRelDetail
          if (
            currControlData.value[currControlData.value.length - 1]?.id !==
            item.id
          ) {
            currControlData.value.push({
              id: item.id,
              subDetail: {
                cnName: item.subDetail.cnName,
                subRelDetail: []
              }
            });
          }
          currControlData.value[
            currControlData.value.length - 1
          ].subDetail.subRelDetail.push(item2);
        }
      });
    }
  }
};

// 新增tab
const inputLabel = (item: any, ind: number) => {
  const arr = tabs.data[currUserId.value][currIndex].codes
    .split(',')
    .filter(Boolean);
  if (arr?.length !== 0) {
    if (!arr?.some((ele: any) => ele === controlList.value[ind].ctlCode)) {
      arr?.push(controlList.value[ind].ctlCode);
    }
  } else {
    arr?.push(controlList.value[ind].ctlCode);
  }
  tabs.data[currUserId.value][currIndex].codes = arr.join(',');
  const tag = `&nbsp;<span style="text-decoration: underline; color: #3598db; font-size: 12pt;">#${item.ctlCnName}#</span>&nbsp;`;
  nextTick(() => {
    console.log('====================================');
    console.log(itemRefs);
    console.log(currUid.value);
    console.log(arr);
    console.log(tabs.data[currUserId.value][currIndex].codes);
    console.log('====================================');

    itemRefs[currUid.value].insertContent(tag);
  });
};

defineExpose({
  tabs
});
</script>

<style lang="less" scoped>
.wrap {
  width: 100%;
  display: grid;
  grid-template-columns: 3fr 1fr;

  .control {
    max-width: 300px;
    padding: 10px 20px 0px;

    section {
      h3 {
        font-weight: 700;
        height: 56px;
        line-height: 56px;
        &::before {
          content: '';
          display: inline-block;
          width: 6px;
          height: 40%;
          margin-right: 10px;
          background: #165dff;
          position: relative;
          top: 7px;
          border-radius: 3px;
        }
      }

      .custom-radio-card {
        background-color: #fff;
      }
      .custom-radio-card:hover,
      .custom-radio-card-checked {
        border-color: rgb(var(--primary-6));
      }
    }
  }
}
</style>
